// oneWayFlight.js - 单程航班API接口
import request from '@/utils/request'
import {downloadExcel} from "@/utils/fileDownload.js";

// 单程航班API接口
const oneWayFlightApi = {
    /**
     * 搜索单程航班
     * @param {Object} searchRequest - 搜索请求参数
     * @returns {Promise} 搜索结果
     */
    async searchOneWayFlights(searchRequest) {
        try {
            return await request.post('/flights/search/oneway', searchRequest)
        } catch (error) {
            console.error('搜索单程航班失败:', error)
            throw error
        }
    },

    /**
     * 导出单程航班搜索结果
     * @param {Object} exportData - 导出数据
     * @returns {Promise} 文件下载
     */
    async exportOneWayFlights(exportData) {
        try {
            console.log('开始导出单程航班:', exportData)

            // 显示加载提示
            ElMessage.info('正在准备导出文件...')

            const response = await request.post('/flights/export/oneway', exportData.searchResponse, {
                params: {
                    exportLowestPriceOnly: exportData.exportOptions?.exportLowestPriceOnly || false
                },
                responseType: 'blob'
            })

            // 生成默认文件名
            const searchRequest = exportData.searchRequest
            const defaultFilename = `单程机票_${searchRequest.departure}-${searchRequest.destination}_${new Date().toISOString().split('T')[0]}.xlsx`

            // 使用文件下载工具下载Excel文件
            const success = await downloadExcel(response.data || response, defaultFilename, response)

            if (success) {
                ElMessage.success('Excel文件导出成功')
                return { success: true, message: '导出成功' }
            } else {
                throw new Error('文件下载失败')
            }
        } catch (error) {
            console.error('导出单程航班失败:', error)
            ElMessage.error(`导出失败: ${error.message}`)
            throw error
        }
    }
}

export default oneWayFlightApi